package com.zlp.security.service;

import com.zlp.entity.User;
import com.zlp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service("userDetailsService")
@Slf4j(topic = "MyUserDetailsServiceImpl")
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("loadUserByUsername.req username={}",username);
        //  1. 查询用户
        User user = userService.loadUserByUsername(username);
        if (Objects.isNull(user)) {
            log.error("User [" + username + "] was not found in db");
            throw new UsernameNotFoundException("User [" + username + "] was not found in db");
        }
        // 密码是加过密
        String password = user.getPassword();
        // 2. 设置权限角色信息
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList
                ("ADMIN,ROLE_abc");
        return new org.springframework.security.core.userdetails.User(username,password, grantedAuthorities);

    }
}
